package com.anhry.app.safety.manage.tjfx.struts.action;

import java.io.ByteArrayOutputStream;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import com.anhry.app.safety.manage.enterprise.bean.TbCorpInfo;
import com.anhry.app.safety.manage.system.bean.TbUser;
import com.anhry.app.safety.manage.system.bean.TbUserDept;
import com.anhry.app.safety.manage.tjfx.bean.vo.TjfxCallManageBean;
import com.anhry.app.safety.manage.tjfx.struts.base.ExportExcel;
import com.anhry.app.safety.manage.tjfx.struts.base.TjfxOaBaseAction;
import com.anhry.app.safety.util.Loggers;
import com.anhry.app.safety.util.Util;
import com.anhry.app.safety.util.UtilMethod;

@Controller
@Scope("prototype")
@SuppressWarnings("unchecked")
public class TjNoticeAction extends TjfxOaBaseAction {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	private Long uId;

	private String acceptCount;

	private List acceptList;

	private String showName;

	private List resultList;

	private List excelList;// excel信息

	private List<TbUserDept> deptList;// 部门列表

	private List<TjfxCallManageBean> pageList;

	private Object[] sumList;

	private List yearList;

	private String tjType;

	private String xmlString;

	private String excelFlag;

	public String getXmlString() {
		return xmlString;
	}

	public void setXmlString(String xmlString) {
		this.xmlString = xmlString;
	}

	public String TjNotice() {
		try {
			TbUser user = (TbUser) this.contextPvd.getSessionAttr(Util.SESSION_ADMINUSER);
			int grade = Integer.parseInt(user.getTbUserGrade().getId() + "");
			StringBuffer hqlBuffer = new StringBuffer("select m.tbUser.tbUserDept.id,");
			hqlBuffer.append(initTime("m.noticeYear")).append(" from TbOaNotice m where 1=1 and m.isDele = 0");// 附加时间
			String excelTitle = "";
		
			if (tjType.equals("0")) {// 安委会统计
				// 条件
				if (grade == 8) {// 区安办
					excelTitle = "公告通知（区安办）";
					hqlBuffer.append(" and m.tbUser.tbUserDept.id = ").append(user.getTbUserDept().getId());
				} else {// 市安办 点击市安办，第一行显示市安办，下面显示各个区安办
					excelTitle = "公告通知（市安办、区安办）";
					hqlBuffer.append(" and (m.tbUser.tbUserDept.deptType = 0 and m.tbUser.tbUserDept.deptGrade = 2 and m.tbUser.tbUserDept.deptClass = 2)  or (m.tbUser.tbUserDept.deptType = 0 and m.tbUser.tbUserDept.deptGrade = 3) ");
				}
			} else if (tjType.equals("1")) {// 科室统计
				if (grade == 4) {// 区科室
					excelTitle = "公告通知（区科室）";
					hqlBuffer.append(" and m.tbUser.tbUserDept.id = ").append(user.getTbUserDept().getId());
				} else {// 市科室 点击市科室，第一行显示市科室，下面显示各个区科室
					excelTitle = "公告通知（市科室、区科室）";
					hqlBuffer.append(" and m.tbUser.tbUserDept.deptType = 1 and (m.tbUser.tbUserDept.deptGrade = 2 or m.tbUser.tbUserDept.deptGrade = 3)");
				}
			} else if (tjType.equals("2")) {// 行业统计
				if (grade == 6 && user.getTbUserDept().getDeptGrade().equals("3")) {// 区行业
					excelTitle = "公告通知（区行业）";
					hqlBuffer.append(" and m.tbUser.tbUserDept.id = ").append(user.getTbUserDept().getId());
				} else if (grade == 5 && user.getTbUserUnit().getDeptGrade().equals("3")) {
					excelTitle = "公告通知（市行业）";
					hqlBuffer.append(" and m.tbUser.tbUserDept.deptSj = ").append(user.getTbUserUnit().getId());
				} else {// 市科室 点击市科室，第一行显示市科室，下面显示各个区科室
					excelTitle = "公告通知（市行业、区行业）";
					hqlBuffer.append(" and (m.tbUser.tbUserDept.deptClass = 1 or m.tbUser.tbUserDept.deptClass = 2) and m.tbUser.tbUserDept.deptType = 2 and (m.tbUser.tbUserDept.deptGrade = 2 or m.tbUser.tbUserDept.deptGrade = 3)");
				}
			} else if (tjType.equals("3")) {// 属地统计
				if (user.getTbUserDept() != null && user.getTbUserGrade().getId() == 7) {// 镇级属地
					excelTitle = "公告通知（乡镇）";
					hqlBuffer.append(" and m.tbUser.tbUserDept.id = ").append(user.getTbUserDept().getId());
				} else if (user.getTbUserUnit() != null && user.getTbUserGrade().getId() == 7) {// 属地
					excelTitle = "公告通知（属地）";
					hqlBuffer.append(" and m.tbUser.tbUserUnit.deptParentId = ").append(user.getTbUserUnit().getId()).append(" and m.tbUser.tbUserDept.deptType = 3");
				} else {// 市科室 点击市科室，第一行显示市科室，下面显示各个区科室
					excelTitle = "公告通知（属地、镇级属地）";
					hqlBuffer.append(" and m.tbUser.tbUserDept.deptClass = 1 and m.tbUser.tbUserDept.deptType = 3 or (m.tbUser.tbUserDept.deptParentId = 1402 or m.tbUser.tbUserDept.deptType = 3)");
				}
			}
			hqlBuffer.append(" group by m.tbUser.tbUserDept.id");
			resultList = (List) this.utilService.getHqlQuery(hqlBuffer.toString());
			getDeptList();
			initPageData();
			if (excelFlag == null || excelFlag.equals("")) {
				result = "tj_notice";
				return SUCCESS;
			} else {
				List<String> titleList = new ArrayList<String>();
				titleList.add("部门名称");
				for (int i = 0; i < yearList.size(); i++) {
					titleList.add(yearList.get(i) + "年");
				}
				titleList.add("合计");
				excelList = new ArrayList();
				for (int i = 0; i < pageList.size(); i++) {
					excelList.add(new Object[] { pageList.get(i).getShowNameParent() + pageList.get(i).getShowName(), pageList.get(i).getYear1(), pageList.get(i).getYear2(), pageList.get(i).getYear3(), pageList.get(i).getYear4(), pageList.get(i).getYear5(), pageList.get(i).getPrivateCount() });
				}
				excelList.add(new Object[] { sumList[0], sumList[1], sumList[2], sumList[3], sumList[4], sumList[5], sumList[6] });
				ExportExcel export = new ExportExcel(excelList, titleList, excelTitle);
				HSSFWorkbook workbook = export.createWorkbook();

				HttpServletResponse response = this.contextPvd.getResponse();
				response.reset();
				response.setContentType("application/x-msdownload");
				response.addHeader("Content-Disposition", "attachment; filename=\"" + new String(excelTitle.getBytes("GB2312"), "iso8859-1") + ".xls\"");
				ByteArrayOutputStream ostream = new ByteArrayOutputStream();
				ServletOutputStream servletOS = response.getOutputStream();
				workbook.write(ostream);
				servletOS.write(ostream.toByteArray());
				servletOS.flush();
				servletOS.close();
				return null;
			}
		} catch (Exception e) {
			e.printStackTrace();
			Loggers.error("TjManageMailAction:getMailSabTj() 出错:" + e);
		}
		return ERROR;
	}

	public void getDeptList() {
		try {
			TbUser user = (TbUser) this.contextPvd.getSessionAttr(Util.SESSION_ADMINUSER);
			int grade = Integer.parseInt(user.getTbUserGrade().getId() + "");
			StringBuffer deptBuffer = new StringBuffer("from TbUserDept d where d.isDele=0 ");
			pageList = new ArrayList<TjfxCallManageBean>();
			if (tjType.equals("0")) {// 安办
				if (grade == 8) {// 区安办
					if (user.getTbUserDept() != null) {
						deptBuffer.append(" and d.id = ").append(user.getTbUserDept().getId());
					} else {
						deptBuffer.append(" and d.id = ").append(user.getTbUserUnit().getId());
					}
					deptList = (List) this.utilService.getHqlQuery(deptBuffer.toString());
				} else {
					deptBuffer.append(" and (d.deptType=0 and d.deptGrade = 3 and d.deptClass = 2 ) or (d.deptType=0 and d.deptGrade = 2 and d.deptClass = 2)").append(" order by d.deptParentId,d.id asc");
					deptList = (List) this.utilService.getHqlQuery(deptBuffer.toString());
				}
			} else if (tjType.equals("1")) {
				if (grade == 4) {// 区科室
					if (user.getTbUserDept() != null) {
						deptBuffer.append(" and d.id = ").append(user.getTbUserDept().getId());
					} else {
						deptBuffer.append(" and d.id = ").append(user.getTbUserUnit().getId());
					}
					deptList = (List) this.utilService.getHqlQuery(deptBuffer.toString());
				} else {
					deptBuffer.append(" and d.deptType =1 and (d.deptGrade = 2 or d.deptGrade = 3)");
					if (user.getTbUserDept() != null && user.getTbUserDept().getDeptGrade().equals("3") && user.getTbUserDept().getDeptType().equals("0")) {// 区科室
						deptBuffer.append(" and d.deptParentId = ").append(user.getTbUserUnit().getId());
					}
					deptBuffer.append(" order by case when d.deptParentId = 5277 then 0 end, d.deptParentId,d.id asc");
					deptList = (List) this.utilService.getHqlQuery(deptBuffer.toString());
				}
			} else if (tjType.equals("2")) {
				if (grade == 6 && user.getTbUserDept().getDeptGrade().equals("3")) {// 区行业
					deptBuffer.append(" and d.id = ").append(user.getTbUserDept().getId());
					deptList = (List) this.utilService.getHqlQuery(deptBuffer.toString());
				} else if (grade == 5 && user.getTbUserUnit().getDeptGrade().equals("2")) {
					deptBuffer.append(" and d.deptSj = ").append(user.getTbUserUnit().getId()).append(" or d.id=").append(user.getTbUserUnit().getId());
					deptBuffer.append(" order by d.id");
					deptList = (List) this.utilService.getHqlQuery(deptBuffer.toString());
				} else {
					deptBuffer.append(" and (d.deptClass = 1 or d.deptClass = 2) and d.deptType =2 and (d.deptGrade = 2 or d.deptGrade = 3)");
					if (user.getTbUserDept() != null && user.getTbUserDept().getDeptGrade().equals("3") && user.getTbUserDept().getDeptType().equals("0")) {// 区科室
						deptBuffer.append(" and d.deptParentId = ").append(user.getTbUserUnit().getId());
					}
					deptBuffer.append(" order by d.deptParentId,d.id asc");
					deptList = (List) this.utilService.getHqlQuery(deptBuffer.toString());
				}
			} else if (tjType.equals("3")) {// 属地
				if (user.getTbUserDept() != null && user.getTbUserGrade().getId() == 7) {// 镇级属地
					deptBuffer.append(" and d.id = ").append(user.getTbUserDept().getId());
					deptList = (List) this.utilService.getHqlQuery(deptBuffer.toString());
				} else if (user.getTbUserUnit() != null && user.getTbUserGrade().getId() == 7) {
					deptBuffer.append(" and d.deptParentId = ").append(user.getTbUserUnit().getId()).append(" and d.deptType = 3");
					deptBuffer.append(" order by d.id");
					deptList = (List) this.utilService.getHqlQuery(deptBuffer.toString());
				} else {
					deptBuffer.append(" and (d.deptClass = 1 and d.deptType = 3 or (d.deptParentId = 1402 and d.deptType = 3))");
					if (user.getTbUserDept() != null && user.getTbUserDept().getDeptGrade().equals("3") && user.getTbUserDept().getDeptType().equals("0")) {// 区科室
						deptBuffer.append(" and d.deptParentId = ").append(user.getTbUserUnit().getId());
					}
					deptBuffer.append(" order by d.deptParentId,d.id asc");
					deptList = (List) this.utilService.getHqlQuery(deptBuffer.toString());
				}
			}
			for (TbUserDept dept : deptList) {
				pageList.add(new TjfxCallManageBean(dept.getId() + "", dept.getDeptName(), 0l, "0", "0", "0", "0", "0", dept.getDeptParentName()));
			}
		} catch (Exception e) {
			e.printStackTrace();
			Loggers.error("TjManageMailAction:getDeptList()出错 :" + e);
		}
	}

	public void initPageData() {
		if (pageList != null) {
			xmlString = "";
			for (TjfxCallManageBean b : pageList) {
				for (int i = 0; i < resultList.size(); i++) {
					Object[] mail = (Object[]) resultList.get(i);
					if (mail[0].toString().equals(b.getShowId())) {
						b.setYear1(mail[1] + "");
						b.setYear2(mail[2] + "");
						b.setYear3(mail[3] + "");
						b.setYear4(mail[4] + "");
						b.setYear5(mail[5] + "");
						b.setPrivateCount(Long.parseLong(b.getYear1()) + Long.parseLong(b.getYear2()) + Long.parseLong(b.getYear3()) + Long.parseLong(b.getYear4()) + Long.parseLong(b.getYear5()));
						xmlString += "<set name='" + b.getShowName() + "' value='" + b.getPrivateCount() + "' />";
					}
				}
			}
		} else {
			xmlString += "<set name=' ' value=' ' />";
		}
		sumList = new Object[] { "合计", "0", "0", "0", "0", "0", "0" };
		if (pageList != null && pageList.size() > 0) {
			for (TjfxCallManageBean bean : pageList) {
				sumList[1] = (Integer.parseInt(bean.getYear1()) + Integer.parseInt(sumList[1] + "")) + "";
				sumList[2] = (Integer.parseInt(bean.getYear2()) + Integer.parseInt(sumList[2] + "")) + "";
				sumList[3] = (Integer.parseInt(bean.getYear3()) + Integer.parseInt(sumList[3] + "")) + "";
				sumList[4] = (Integer.parseInt(bean.getYear4()) + Integer.parseInt(sumList[4] + "")) + "";
				sumList[5] = (Integer.parseInt(bean.getYear5()) + Integer.parseInt(sumList[5] + "")) + "";
				sumList[6] = (Integer.parseInt(bean.getPrivateCount() + "") + Integer.parseInt(sumList[6] + "")) + "";
			}
		}
	}

	public String initTime(String timeCell) {
		Calendar calendar = Calendar.getInstance();
		int nowYear = calendar.get(Calendar.YEAR);
		StringBuffer tempBuffer = new StringBuffer();
		yearList = new ArrayList<Object>();
		for (int i = nowYear; i > nowYear - 5; i--) {// 往前推5年
			yearList.add(i);
			tempBuffer.append(" sum(case when ").append(timeCell).append(" = ").append(i).append(" then 1 else 0 end),");
		}
		return tempBuffer.substring(0, tempBuffer.lastIndexOf(","));
	}

	public String noticeAccept() {
		try {
			StringBuffer hqlString = new StringBuffer();
			if ((uId != null && uId != 0l) && (acceptCount != null && !acceptCount.equals("0"))) {// 要查看的发件人id不为空并且总数不等于0
				hqlString.append("select u.corp_id,u.user_id,u.user_type,COUNT(*) FROM tb_oa_notice_user u LEFT JOIN tb_oa_notice n ON u.notice_id = n.id WHERE n.notice_user = ").append(uId).append(" GROUP BY u.corp_id,u.user_id,u.user_type");
				List list = (List) this.utilService.getObjectBySql(hqlString.toString(), 0, 0);
				TbUser user = new TbUser();
				TbCorpInfo dept = new TbCorpInfo();
				acceptList = new ArrayList();
				if (list.size() > 0) {
					showName = this.contextPvd.decode(showName);
					for (int i = 0; i < list.size(); i++) {
						Object[] result = new Object[] { "", 0, "" };
						Object[] obj = (Object[]) list.get(i);
						if (obj[2].toString().equals("0")) {// 接收为管理机构
							user = (TbUser) this.utilService.getObjectById(TbUser.class, Long.parseLong(obj[1].toString()));
							result[0] = user.getUserName();
						} else if (obj[2].toString().equals("1")) {// 接收为企业
							dept = (TbCorpInfo) this.utilService.getObjectById(TbCorpInfo.class, Long.parseLong(obj[0].toString()));
							result[0] = dept.getCorpName();
						}
						result[1] = obj[3];
						result[2] = showName;
						acceptList.add(result);
					}
				}
				result = "tj_notice_accept";
				return SUCCESS;
			}
		} catch (Exception e) {
			e.printStackTrace();
			Loggers.error("TjNoticeAction:noticeAccept 出错" + e);
		}
		return ERROR;
	}

	public String getAcceptCount() {
		return acceptCount;
	}

	public void setAcceptCount(String acceptCount) {
		this.acceptCount = acceptCount;
	}

	public List getAcceptList() {
		return acceptList;
	}

	public void setAcceptList(List acceptList) {
		this.acceptList = acceptList;
	}

	public String getExcelFlag() {
		return excelFlag;
	}

	public void setExcelFlag(String excelFlag) {
		this.excelFlag = excelFlag;
	}

	public List getExcelList() {
		return excelList;
	}

	public void setExcelList(List excelList) {
		this.excelList = excelList;
	}

	public List<TjfxCallManageBean> getPageList() {
		return pageList;
	}

	public void setPageList(List<TjfxCallManageBean> pageList) {
		this.pageList = pageList;
	}

	public List getResultList() {
		return resultList;
	}

	public void setResultList(List resultList) {
		this.resultList = resultList;
	}

	public String getShowName() {
		return showName;
	}

	public void setShowName(String showName) {
		this.showName = showName;
	}

	public Object[] getSumList() {
		return sumList;
	}

	public void setSumList(Object[] sumList) {
		this.sumList = sumList;
	}

	public String getTjType() {
		return tjType;
	}

	public void setTjType(String tjType) {
		this.tjType = tjType;
	}

	public Long getUId() {
		return uId;
	}

	public void setUId(Long id) {
		uId = id;
	}

	public List getYearList() {
		return yearList;
	}

	public void setYearList(List yearList) {
		this.yearList = yearList;
	}

	public void setDeptList(List<TbUserDept> deptList) {
		this.deptList = deptList;
	}
}
